package com.zc.timedown.service.impl;

import com.zc.common.core.domain.entity.SysDictData;
import com.zc.system.service.ISysDictDataService;
import com.zc.timedown.dto.CategoryDTO;
import com.zc.timedown.mapper.CategoryMapper;
import com.zc.timedown.service.ApiCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * ClassName:ApiCategoryServiceImpl
 * Description:
 * DateTime: 2025/10/28 15:31
 * Author: zc
 * Version: 1.0
 */
@Service
public class ApiCategoryServiceImpl implements ApiCategoryService {
    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private ISysDictDataService dictDataService;
    @Override
    public List<SysDictData> selectCategoryList(String dictType, Long userId) {
        return categoryMapper.selectCategoryList(dictType, userId);
    }


    @Override
    public int insertCategory(SysDictData category) {
        return dictDataService.insertDictData(category);
    }

    @Override
    public int updateCategory(SysDictData category, Long userId) {
        // 验证用户权限
        if (!checkCategoryPermission(category.getDictCode(), userId)) {
            throw new RuntimeException("无权限修改该分类");
        }
        return dictDataService.updateDictData(category);
    }

    @Override
    public int deleteCategoryByIds(Long[] dictCodes, Long userId) {
        int count = 0;
        for (Long dictCode : dictCodes) {
            // 检查是否可以删除
            if (!checkCategoryDeletable(dictCode)) {
                throw new RuntimeException("默认分类不能删除");
            }
            // 验证用户权限
            if (!checkCategoryPermission(dictCode, userId)) {
                throw new RuntimeException("无权限删除该分类");
            }
            count += dictDataService.deleteDictDataById(dictCode);
        }
        return count;
    }

    @Override
    public boolean checkCategoryDeletable(Long dictCode) {
        SysDictData dictData = dictDataService.selectDictDataById(dictCode);
        // 默认分类不能删除
        return !"Y".equals(dictData.getIsDefault());
    }

    /**
     * 检查用户是否有权限操作分类
     */
    private boolean checkCategoryPermission(Long dictCode, Long userId) {
        SysDictData dictData = dictDataService.selectDictDataById(dictCode);
        if (dictData == null) {
            return false;
        }

        // 默认分类任何人都可以查看，但不能修改或删除
        if ("Y".equals(dictData.getIsDefault())) {
            return false; // 默认分类不允许操作
        }

        // 用户自定义分类需要验证创建者
        return String.valueOf(userId).equals(dictData.getCreateBy());
    }
}
